<template>
    <div>
        <div id="wrapper" class="pb-150">
            <!--顶部fixed部分-->
            <div class="fixed-top fixed-box">
                <div class="top-header border-bottom">
                    <div class="top-back"><a @click="goBack"></a></div>
                    <h2 class="f36">订单详情</h2>
                    <div class="top-right"></div>
                </div>
            </div>
            <div class="mt-97">
                <div class="bg-m1 f32 color-fff order_top_tip clearfix" v-if="state === '待付款'">
          <span class="icon_wait icon_mon">未付款&nbsp; <a class="bg-fff color-m1" href="javascript:void(0)"
                                                        @click="goPay">去支付</a>&nbsp; 剩余时间：{{restTime}}</span>
                </div>
                <div class="bg-m1 f32 color-fff order_top_tip" v-else-if="state === '已付款'">
          <span class="icon_mon">您已付款，请&nbsp; <a class="bg-fff color-m1"
                                                 href="javascript:void(0)" @click="goToServe">联系客服</a>&nbsp; 交易</span>
                </div>
                <div class="bg-2a f32 color-fff order_top_tip" v-else-if="state === '交易成功'">
                    <span class="icon_firm">交易成功</span>
                </div>
                <div class="bg-999 f32 color-fff order_top_tip" v-else-if="state === '交易取消'">
                    <span class="icon_fail">交易取消</span>
                </div>
            </div>
            <div class="detail_container bg-fff clearfix border-bottom">
                <img class="game_logo fl" :src="detail.goodsImg">
                <div>
                    <p class="titl f30 color-000">{{detail.title}}</p>
                    <p class="f28 mt-20 color-000">￥{{detail.totalAmount}}</p>
                </div>
            </div>
            <div
               v-if="tradeDescription.length"
               @click="showTradeDescription=true"
               class="detail_explain px-30 bg-fff border-bottom"><span
               class="exp-titl fl f28 color-000">交易说明</span><i
               class="ico fr"></i></div>
            <div class="detail_container bg-fff mt-20 border-bottom">
                <p class="f30 mb-30"><span class="color-666 pr-30">游戏区服</span><span
                   class="color-000">{{detail.serviceProviderName}} /{{detail.regionName}}/ {{detail.serverName}}</span>
                </p>
                <p class="f30"><span class="color-666 pr-30">商品类型</span><span class="color-000">游戏币</span></p>
            </div>
            <div class="detail_container bg-fff border-bottom">
                <p class="f30 mb-30"><span class="color-666 pr-30">商品价格</span><span
                   class="color-666 fr">￥{{detail.price}}</span></p>
                <p class="f30"><span class="color-666 pr-30">商品件数</span><span
                   class="color-666 fr">x{{detail.num}}</span></p>
            </div>
            <div class="total_container bg-fff border-bottom">
                <p class="f30 mb-30"><span class="color-m1 fr ml-30">￥{{detail.totalAmount}}</span><span
                   class="color-666 fr">合计金额</span>
                </p>
            </div>
            <div class="detail_container bg-fff  mt-20">
                <p class="f30 mb-30"><span class="color-666 pr-30">订单编号</span>
                    <span class="color-666">{{detail.orderId}}</span>
                    <a class="copy ml-20 color-666 f24" :data-clipboard-text="detail.orderId" @click="copy" ref="mgCoy">复制</a>
                </p>
                <p class="f30"><span class="color-666 pr-30">下单时间</span>
                    <span class="color-666"
                        v-if="detail.createTimeString"
                        v-text="detail.createTimeString"
                ></span></p>
            </div>
            <div class="fixed-bottom mancon-btn pr-30 py-20 bg-fff border-top" v-if="state === '待付款'">
                <a class="f30 color-fff border border-color bg-m1 fr" @click="goPay">去付款</a>
                <a class="f30 color-666 border border-color666 cancel fr" @click="showMessageConfirm = true">取消订单</a>
            </div>
            <div class="fixed-bottom mancon-btn pr-30 py-20 bg-fff border-top"
                 v-if="state === '已付款' || state === '交易成功'"><a
               class="f30 color-m1 border border-color cancel fr" href="javascript:void(0)"
               @click="goToServe">联系客服</a>
                <i class="titcur fr" @click="alertMessage"></i>
            </div>
            <div class="maskdiv" v-if="showTradeDescription" @click="showTradeDescription=false"></div>
            <!--交易说明-->
            <div class="sv-guarantee fixed-bottom border-top bg-fff  " v-if="showTradeDescription"
                 style="z-index: 60;overflow: scroll" :style="{'max-height': .6 * height + 'px'}">
                <div class="scgtee-titl f32 color-666 border-bottom">
                    <a class="close mr-30" @click="showTradeDescription=false"></a>交易说明
                </div>
                <div class="ift-list color-333 f28 px-30 py-20 mg_trade_description" v-html="tradeDescription">
                </div>
            </div>
            <div class="message_confirm" v-if="showMessageConfirm">
                <div class="maskdiv" style="z-index: 1" v-if="showMessageConfirm"
                     @click="showMessageConfirm=false"></div>
                <!--取消订单-->
                <div class="dialog-box bg-fff" style="margin: auto; z-index: 2">
                    <div class="dialog-main">
                        <div class="dialog-body color-000" id="errortx">确定取消订单？</div>
                        <div class="dialog-foot">
                            <a class="dialog_close border-right color-m1" href="javascript:void(0);"
                               @click="showMessageConfirm=false">我再想想</a>
                            <a class="dialog_close color-000" href="javascript:void(0);" @click="cancelOrder">去意已决</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
  import {getMenu} from './buyerStoreMenu'
  import Clipboard from 'clipboard'

  export default {
    data() {
      return {
        showMessageConfirm: false,
        height: window.innerHeight,
        showTradeDescription: false, // 是否显示交易说明
        tradeDescription: '', // 交易说明内容
        params: this.$route.params,
        restTime: null, // 创建时间 + 30 * 60 * 1000 - 当前时间
        clipboard: null,
        state: '', // 订单的状态
        param: '1', // 返回订单列表的状态
        detail: {}
      }
    },
    created() {
      this.$indicator.open({
        spinnerType: 'fading-circle'
      })
    },
    destroy() {
      this.$indicator.close() // 关闭加载中提示
    },
    mounted() {
      this.init()
      this.clipboard = new Clipboard(this.$refs['mgCoy']);
    },
    methods: {
      alertMessage() {
        const qq = this.detail.serviceQQ || ''
        if (!!qq) {
          this.$messagebox({
            message: "如点击联系客服无法启动QQ，请加客服QQ号(" + qq + ")"
          })
        } else {
          this.$messagebox({
            message: "该订单正在分配客服"
          })
        }
      },
      goToServe() {
        const qq = this.detail.serviceQQ || ''
        if(/baidu/i.test(navigator.userAgent.toLowerCase())||/MicroMessenger/i.test(navigator.userAgent.toLowerCase())){
          this.$messagebox({
            message: "如点击联系客服无法启动QQ，请加客服QQ号("+ qq +")"
          })
        }else {
          window.location.assign('mqqwpa://im/chat?chat_type=wpa&uin=' + qq + '&version=1&src_type=web&web_src=oicqzone.com')
        }
      },
      /* 返回到列表页 */
      goBack() {
      	var param =  this.param
      	if(param=='4'){
	        param = '-1'
        }else  if(param=='2'){
	        param = '1|2'
        }else if(param=='1'){
            param = '0'
        }
        this.$router.push({
          path: '/vue/buyerCenter/buyOrderList/' + param
        })
      },
      copy() {
        this.clipboard.on('success', e => {
          this.$toast('订单号已复制到剪贴板')
          e.clearSelection();
        });
        this.clipboard.on('error', e => {
          this.$toast('复制失败，请尝试长按复制')
        });
      },
      /* 去支付 */
      goPay() {
        this.$indicator.open()
        let orderId = this.params.orderId
        let returnUrl = location.protocol + '//' + location.hostname + '/vue/buyerCenter/buyerMobCoinOrder/' + orderId
        this.$http.get('/api/mobile-order-service/rs/payment/mypay', {params: {orderId, returnUrl}}).then(res => {
          window.location.href = res.data.url
        }).then(() => {
          this.$indicator.close()
        })
      },
      /* 取消订单 */
      cancelOrder() {
        this.showMessageConfirm = false
        this.$indicator.open()
        this.$http.post('/api/mobile-order-service/rs/buyer/order/cancel', {orderId: this.params.orderId}).then(({data: res}) => {
          if (res.success) {
            this.setDetail()
          } else {
            this.$toast(res.responseStatus.message)
          }
        }).then(() => {
          this.$indicator.close()
        })
      },
      init() {
        /* 获取订单详情 */
        this.setDetail().then(() => {
          /* 获取描述 */
          let params = {gameId: this.detail.gameId, goodsType: this.detail.goodsType}
          this.$http.get(this.$CONSTANTS.APICategory + 'goodsTypeGameService/selectTradeDescription', {params}).then(res => {
            this.tradeDescription = res.data.tradeDescription || ''
          }).then(() => {
            this.$indicator.close()
          })
        })
      },
      /* 配置详情 */
      setDetail() {
        return this.$http.get(`/api/mobile-order-service/rs/buyer/order/${this.params.orderId}`).then(res => {
          if (!res.data.success) {
            alert(res.data.responseStatus.message)
            location.href = '/'
          } else {
            res.body.result.createTime = new Date(res.body.result.createTime) // 创建时间
            res.body.result.currentTime = new Date(res.body.currentTime) // 当前时间
            res.body.result.createTimeString = this._turnTime(res.body.result.createTime) // 格式化创建时间
            this.detail = res.body.result // 配置详情信息
            this.state = getMenu(this.detail.status).name // 获取该订单的状态名称
            this.param = getMenu(this.detail.status).param
            if (this.state === '待付款')
              this.showRestTime(this.detail.createTime, this.detail.currentTime)
          }
        })
      },
      /* 计算剩余时间 */
      showRestTime(createDate, currentTime) {
        function _() {
          let rest = (createDate.getTime() + 30 * 60 * 1000 - currentTime.getTime()) / 1000
          if (rest <= 0) rest = 0
          this.restTime = this._turnNum(parseInt(rest / 60)) + '分' + this._turnNum(parseInt(rest % 60)) + '秒'
          currentTime = new Date(currentTime.getTime() + 1000)
        }

        _.apply(this)
        setInterval(() => {
          _.apply(this)
        }, 1000)
      },
      _turnNum(num) {
        if (num < 10) return '0' + num
        return num
      },
      _turnTime(date) {
        return date.getFullYear() + '-' +
          this._turnNum(date.getMonth() + 1) + '-' +
          this._turnNum(date.getDate()) + ' ' +
          this._turnNum(date.getHours()) + ':' +
          this._turnNum(date.getMinutes()) + ':' +
          this._turnNum(date.getSeconds())
      }
    }
  }
</script>
<style src="css/member/member-order.css" ></style>
<style>
    .mg_trade_description img {
        max-width: 100%;
    }
</style>
<style scoped>
    .message_confirm {
        position: fixed;
        display: flex;
        align-items: center;
        width: 100%;
        height: 100%;
        top: 0;
        z-index: 1000;
    }
</style>